package gazzera.node.core.peer;

import gazzera.node.core.*;
import gazzera.node.core.messages.*;

class PeerWriter implements Runnable
{
	private Peer peer;
	private ICore core;

	public PeerWriter(Peer peer, ICore core)
	{
		super();
		this.peer = peer;
		this.core = core;
	}

	@Override
	public void run()
	{
		try
		{
			while (true)
			{
				Object o = peer.outbox.take();
				if(o instanceof Message)
				{
					peer.send((Message)o);
				}
				else if (o instanceof DataPumpSource)
				{
					DataPumpSource src = (DataPumpSource)o;
					DataPump pump = new DataPump(peer, src, core);
					ThreadRunner.start(pump, "DataPump", true);
				}
				else if (o instanceof Poison)
				{
					throw new Exception("Writer thread poisoned");
				}
				else
				{
					System.err.println("Unknown object in outbox "+o);
				}
			}
		}
		catch (Exception e)
		{
			// the writer thread is diyng, should we ensure the peer is closed ?
			peer.close();
		}

	}

}
